#!/bin/sh
%BUTCH_CONFIG
retries=5
butch_cache_dir="$C"
tmp=/tmp/butchdl.$$
rc=0
append() {
eval "$1=\"\${$1} \$2\""
eval "$1=\${$1# }"
}

download() {
	local url="$1"
	local out="$2"
	if [ "$USE_CURL" = 1 ] ; then
		curl -c /dev/null -C - --retry $retries -k -L "$url" -o "$out"
	else
		if ! wget --help 2>&1 | grep BusyBox > /dev/null ; then
			append wgetflags "--tries=$retries"
			append wgetflags --no-check-certificate
		fi
		wget $wgetflags -O "$out" -c "$url"
	fi
}

cleanup() {
	[ -e "$tmp" ] && { cat $tmp ; rm $tmp ; }
}

echo "in case the download process was killed, see $tmp for wget/curl output"
for url in %BUTCH_MIRROR_URLS ; do
if ! download "$url" "$butch_cache_dir/%BUTCH_TARBALL".wip >$tmp 2>&1 ; then
	rc=1
	grep 404 < $tmp > /dev/null && rc=44
	cleanup
else
	mv "$butch_cache_dir"/"%BUTCH_TARBALL".wip \
	   "$butch_cache_dir"/"%BUTCH_TARBALL"
	rc=0
	break
fi
done
cleanup
exit $rc
